package com.ext.aic.box.wx.reply;

import android.content.Context;

import com.ext.aic.AICApplication;
import com.ext.aic.beans.box.NotificationMessage;
import com.ext.aic.beans.params.AgentReplyParams;
import com.ext.aic.beans.response.AgentReplyResponse;
import com.ext.aic.box.WindowManager;
import com.ext.aic.box.model.ClientUIConstants;
import com.ext.aic.box.wx.WxDbHelper;
import com.ext.aic.box.wx.WxViews;
import com.ext.aic.constants.EBusConstants;
import com.ext.aic.events.OnAccessibilityServiceEvent;
import com.ext.aic.handler.AccessibilityClickHandler;
import com.ext.aic.utils.BoxUtils;
import com.ext.aic.utils.RedirectUtils;
import com.eyinfo.android_pure_utils.ebus.EBus;
import com.eyinfo.android_pure_utils.ebus.SubscribeEBus;
import com.eyinfo.android_pure_utils.utils.ObjectJudge;
import com.eyinfo.android_pure_utils.utils.PixelUtils;

import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedDeque;

import lombok.Getter;

public class ReplyManager extends WindowManager {

    private WxDbHelper dbHelper = new WxDbHelper();
    private WxViews wxViews = new WxViews();
    private boolean singleReplyDetecting = false;
    @Getter
    private boolean replyDetecting = false;
    @Getter
    private Deque<NotificationMessage> messageDeque = new ConcurrentLinkedDeque<>();
    private Set<Long> messageIds = new HashSet<>();
    @Getter
    private AgentReplyResponse currentReplyResponse;
    @Getter
    private AgentReplyParams currentReplyParams;

    //step1 无障碍建立连接后初始化
    public void init() {
        super.onCreate();
        EBus.getInstance().registered(this);
    }

    //step2 当接收到消息且其它任务队列为空时开始检测
    public void detectionReply(NotificationMessage notificationMessage) {
        OnAccessibilityServiceEvent serviceEvent = BoxUtils.getInstance().getServiceEvent();
        if (!serviceEvent.isConversationAnalyzing()) {
            if (!replyDetecting) {
                replyDetecting = true;
                List<NotificationMessage> messageList = dbHelper.findStayReplyMessageList();
                if (!ObjectJudge.isNullOrEmpty(messageList)) {
                    for (NotificationMessage message : messageList) {
                        if (messageIds.contains(message.getId())) {
                            continue;
                        }
                        messageIds.add(message.getId());
                        messageDeque.add(message);
                    }
                }
                dbHelper.removeInvalidMessage();
            }
            if (notificationMessage != null) {
                if (!messageIds.contains(notificationMessage.getId())) {
                    messageIds.add(notificationMessage.getId());
                    messageDeque.add(notificationMessage);
                }
            }
            detecting();
        }
    }

    //step3 任务队列的递归检测
    private void detecting() {
        if (messageDeque.isEmpty()) {
            singleReplyDetecting = false;
            replyDetecting = false;
            return;
        }
        if (singleReplyDetecting) {
            return;
        }
        singleReplyDetecting = true;
        //step4 取出队列消息尝试获取回复数据（进入聊天窗口后再次校验取的消息是否完整，如果不完整在后续的步骤中再次请求回复内容）
        NotificationMessage message = messageDeque.poll();
        messageIds.remove(message.getId());
        RedirectUtils.getInstance().startWeChat(AICApplication.getInstance().getApplicationContext());
        EBus.getInstance().post(EBusConstants.getAiChatData, message);
    }

    @SubscribeEBus(receiveKey = {EBusConstants.getAiChatDataSuccess})
    public void onGetAiChatDataSuccessEvent(AgentReplyParams params, AgentReplyResponse response) {
        currentReplyParams = params;
        currentReplyResponse = response;
        replyDetecting = false;
        //step5 模拟点击搜索按钮
        simulatedClickSearch();
    }

    private void simulatedClickSearch() {
        Context applicationContext = AICApplication.getInstance().getApplicationContext();
        OnAccessibilityServiceEvent serviceEvent = BoxUtils.getInstance().getServiceEvent();
        ClientUIConstants clientUIConstants = serviceEvent.getClientUIConstants();
        int screenWidth = clientUIConstants.getScreenWidth();
        int statusHeight = clientUIConstants.getStatusHeight();
        int headerHeight = clientUIConstants.getHeaderHeight();
        int conversationItemHeight = clientUIConstants.getConversationItemHeight();
        int loginStatusHeight = clientUIConstants.getLoginStatusHeight();
        int right = PixelUtils.dip2px(applicationContext, 65);

        float x = screenWidth - right;
        float y = statusHeight + (headerHeight / 2f);

        AccessibilityClickHandler clickHandler = new AccessibilityClickHandler();
        clickHandler.clickAtPoint(serviceEvent.getService(), x, y);
    }

    @SubscribeEBus(receiveKey = {EBusConstants.getAiChatDataFail})
    public void onGetAiChatDataFailEvent() {
        replyFinish();
    }

    public void replyFinish() {
        singleReplyDetecting = false;
        currentReplyParams = null;
        currentReplyResponse = null;
        replyDetecting = false;
    }
}
